<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { BusGroupVO } from '#/api/register/bus/group/model';

import { onActivated, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import { Badge, message, Modal, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
  busExport,
  busInfo,
  busPage,
  busRemove,
  busUpdateConfirmStatus,
} from '#/api/register/bus/group';
import { changeLogUnReadCount } from '#/api/register/bus/log';
import { taskInfo } from '#/api/register/bus/task';
import { DetailsModal } from '#/components/modal';
import { TableSwitch } from '#/components/table';
import { commonDownloadExcel } from '#/utils/file/download';

import busTableDrawer from './components/bus-table-drawer.vue';
import { columns, detailsSchema, querySchema } from './group';

const { hasAccessByCodes } = useAccess();

const route = useRoute();
const router = useRouter();
const taskName = ref<string>();
const logUnReadCount = ref<number>(0);

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 100,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3',
  fieldMappingTime: [
    [
      'startAddressMap',
      [
        'startCountryCode',
        'startProvinceCode',
        'startCityCode',
        'startDistrictCode',
      ],
      null,
    ],
    [
      'startTime',
      ['startTimeStart', 'startTimeEnd'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        await getLogUnreadCount();

        return await busPage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
          taskId: route.query.taskId,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'bus-task-group-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [BugTaskGroupDetailsModal, modalApi] = useVbenModal({
  connectedComponent: DetailsModal,
});

function handlePreview(record: BusGroupVO) {
  modalApi.setData(record);
  modalApi.open();
}

// function handleAdd() {
//   drawerApi.setData({});
//   drawerApi.open();
// }

async function handleDelete(row: BusGroupVO) {
  console.log(row);
  await busRemove(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: BusGroupVO) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await busRemove(ids);
      await tableApi.query();
    },
  });
}

function handleDownloadExcel() {
  commonDownloadExcel(
    busExport,
    taskName.value || '巴士任务明细',
    {
      ...tableApi.formApi.form.values,
      taskId: route.query.taskId,
    },
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}

// 查看变更日志
async function getLogUnreadCount() {
  logUnReadCount.value =
    (await changeLogUnReadCount({ taskId: route.query.taskId })) ?? 0;
}

function handleViewChangeLog() {
  router.push({
    path: '/register/busChangeLog',
    query: {
      taskId: route.query.taskId,
    },
  });
}

// 查看巴士列表
const [BusTableDrawer, busTableDrawerApi] = useVbenDrawer({
  connectedComponent: busTableDrawer,
  destroyOnClose: true,
});

function handleViewBusNum(row: BusGroupVO) {
  busTableDrawerApi.setData({
    taskName: taskName.value,
    id: row.id,
    groupId: row.groupId,
    groupName: row.groupName,
  });
  busTableDrawerApi.open();
}

// 修改巴士确认状态
async function confirmStatusUpdate(row: BusGroupVO) {
  await busUpdateConfirmStatus({
    id: row.id,
    confirmStatus: row.confirmStatus,
  });
}

const { setTabTitle } = useTabs();
onMounted(async () => {
  const task = await taskInfo(route.query.taskId as string);
  if (task) {
    tableApi?.formApi.updateSchema([
      {
        fieldName: 'groupId',
        componentProps: {
          exhibitionId: task.exhibitionId,
        },
      },
    ]);
    taskName.value = `${task.name}`;
    setTabTitle(`巴士任务：${task.name}`);
  } else {
    message.warning('查无此巴士任务');
    await router.replace('/register/busTask');
  }
});

onActivated(() => {
  getLogUnreadCount();
});
</script>

<template>
  <Page
    :auto-content-height="true"
    :content-class="`${logUnReadCount > 0 ? 'unread' : ''}`"
  >
    <BasicTable>
      <template #table-title>
        <main-title :text="taskName" />
      </template>
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['bus:manager:export']"
            @click="handleDownloadExcel"
          >
            {{ $t('pages.common.export') }}
          </a-button>
          <Badge v-if="logUnReadCount > 0" :count="logUnReadCount">
            <a-button
              v-access:code="['bus:changeLog:list']"
              @click="handleViewChangeLog"
            >
              变更记录
            </a-button>
          </Badge>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['bus:manager:remove']"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <!--<a-button-->
          <!--  type="primary"-->
          <!--  v-access:code="['bus:manager:add']"-->
          <!--  @click="handleAdd"-->
          <!--&gt;-->
          <!--  {{ $t('pages.common.add') }}-->
          <!--</a-button>-->
        </Space>
      </template>
      <template #busItemNum="{ row }">
        <a-button
          v-if="hasAccessByCodes(['bus:item:list'])"
          type="link"
          @click="handleViewBusNum(row)"
        >
          {{ row.busItemNum }}
        </a-button>
        <span v-else>{{ row.busItemNum }}</span>
      </template>
      <template #confirmStatus="{ row }">
        <TableSwitch
          v-model:value="row.confirmStatus"
          :api="() => confirmStatusUpdate(row)"
          :checked-value="1"
          :checked-text="undefined"
          :un-checked-value="0"
          :un-checked-text="undefined"
          :disabled="!hasAccessByCodes(['bus:manager:changeConfirmStatus'])"
          @reload="tableApi.query()"
        />
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['bus:manager:query']"
            @click.stop="handlePreview(row)"
          >
            {{ $t('pages.common.info') }}
          </ghost-button>
          <ghost-button
            v-access:code="['bus:item:list']"
            :disabled="row.status === '1'"
            @click.stop="handleViewBusNum(row)"
          >
            巴士
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['bus:manager:remove']"
              :disabled="row.status === '1'"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <BusTableDrawer @reload="tableApi.query()" />
    <BugTaskGroupDetailsModal :columns="detailsSchema()" :api="busInfo" />
  </Page>
</template>

<style lang="less" scoped>
:deep(.vxe-toolbar) {
  margin-top: 10px !important;
}
</style>
